package com.xy.tianyu.module.picture.fragment

import androidx.lifecycle.rxLifeScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.xy.tianyu.LazyLoadBaseFragment
import com.xy.tianyu.R
import com.xy.tianyu.module.picture.adapter.PicSetAdapter
import com.xy.tianyu.module.picture.bean.PicSetBean
import com.xy.tianyu.module.picture.bean.PicSetItem
import com.xy.tianyu.network.Api
import kotlinx.android.synthetic.main.fragment_pic_set.*
import rxhttp.RxHttp
import rxhttp.toClass

/**
 * @time 2020/9/30 9:53
 * @class 描述:
 */
class PicSetFragment :LazyLoadBaseFragment(){
    private var pageIndex = 0
    private var picSetList = mutableListOf<PicSetItem>()
    private lateinit var picSetAdapter: PicSetAdapter
    override fun setContentView(): Int {
        return R.layout.fragment_pic_set
    }

    override fun lazyLoad() {
        ry_pic_set.layoutManager = LinearLayoutManager(activity)
        picSetAdapter = PicSetAdapter(R.layout.item_pic_set,picSetList)
        ry_pic_set.adapter = picSetAdapter

        request(true)

        refresh_pic_set.setOnRefreshListener {
            pageIndex = 0
            request(true)
        }

        refresh_pic_set.setOnLoadMoreListener {
            pageIndex++
            request(false)
        }

    }

    override fun stopLoad() {

    }

    private fun request(isRefresh:Boolean){
        rxLifeScope.launch({
            if (isRefresh){
                picSetList.clear()
                picSetAdapter.notifyDataSetChanged()
            }

            val picSetBean = getPicSetData()
            val list = picSetBean.items
            if (!list.isNullOrEmpty()){
                picSetList.addAll(list)
                picSetAdapter.notifyDataSetChanged()
            }
        },{
            ToastUtils.showShort(it.message)
        },{},{
            refresh_pic_set.finishRefresh()
            refresh_pic_set.finishLoadMore()
        })
    }

    private suspend fun getPicSetData():PicSetBean{
       return RxHttp.get(Api.DAY_DAY_SEARCH_PICTURE_BASE_URL+Api.DAY_DAY_SEARCH_PICTURE_PICSET_URL+pageIndex)
            .toClass<PicSetBean>()
            .await()
    }
}